import { ApiResponse } from '../models/types';

import { URLS } from '../models/enums';

export const fetchCharacter = (name: string, page: number = 1, options: { signal: AbortSignal }): Promise<ApiResponse> => {
    return fetch(`${URLS.API_URL}/?name=${name}&page=${page}`, { signal: options.signal })
        .then((response) => {
            if(!response.ok) {
                if(response.status === 404) {
                    throw new Error(`Can't find character with name ${name}...`);
                } else {    
                    throw new Error(`Something went wrong...`);
                }
            }
            return response.json();
        })
        .catch((error) => {
            throw error;
        });
}